"""
用户管理API接口
"""
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session, joinedload
from sqlalchemy import or_, and_
from pydantic import BaseModel, EmailStr
from typing import Optional, List
from datetime import datetime

from core.database import get_db
from core.logging_config import get_logger, log_api_request
from core.exceptions import (
    ValidationError, DataNotFoundError, DataAlreadyExistsError,
    AuthenticationError, AuthorizationError
)
from core.auth import (
    get_current_user, get_current_active_user,
    require_permissions, require_role, require_admin
)
from models.user import User
from services.user_management_service import UserManagementService

# 路由器
users_router = APIRouter(tags=["用户管理"])

# 日志记录器
logger = get_logger("petition_users")


class UserCreate(BaseModel):
    """用户创建模型"""
    username: str
    email: EmailStr
    password: str
    full_name: Optional[str] = None
    phone: Optional[str] = None
    role_ids: Optional[List[int]] = []


class UserUpdate(BaseModel):
    """用户更新模型"""
    email: Optional[EmailStr] = None
    full_name: Optional[str] = None
    phone: Optional[str] = None
    role_ids: Optional[List[int]] = None
    is_active: Optional[bool] = None


class UserResponse(BaseModel):
    """用户响应模型"""
    id: int
    username: str
    email: str
    full_name: Optional[str] = None
    phone: Optional[str] = None
    is_active: bool
    is_superuser: bool
    created_at: datetime
    last_login: Optional[datetime] = None
    login_count: int
    role: str




class PasswordResetRequest(BaseModel):
    """密码重置请求模型"""
    user_id: int


class PasswordResetResponse(BaseModel):
    """密码重置响应模型"""
    new_password: str
    message: str


class PasswordChangeRequest(BaseModel):
    """密码修改请求模型"""
    current_password: str
    new_password: str


class PasswordChangeResponse(BaseModel):
    """密码修改响应模型"""
    message: str


class UserStatsResponse(BaseModel):
    """用户统计响应模型"""
    total_users: int
    active_users: int
    inactive_users: int
    role_statistics: dict
    today_new: int
    week_new: int


# 创建独立的统计路由器，避免路由冲突
user_stats_router = APIRouter(prefix="/api/user-stats", tags=["用户统计"])

@user_stats_router.get("/statistics", response_model=UserStatsResponse)
@log_api_request("get_user_statistics")
async def get_user_statistics(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取用户统计信息"""
    
    # 只有管理员才能查看统计信息
    if not current_user.is_superuser:
        raise AuthorizationError("只有管理员才能查看用户统计")
    
    user_service = UserManagementService(db)
    stats = user_service.get_user_statistics()
    
    return UserStatsResponse(**stats)


@users_router.get("/", response_model=dict)
@log_api_request("list_users")
async def list_users(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    role: Optional[str] = Query(None, description="角色过滤"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取用户列表"""
    
    # 只有管理员才能访问用户管理
    if not current_user.is_superuser:
        raise AuthorizationError("只有管理员才能访问用户管理")
    
    user_service = UserManagementService(db)
    result = user_service.get_users(
        page=page,
        size=size,
        search=search,
        role=role,
        is_active=is_active
    )
    
    # 转换用户数据为响应格式
    users_data = []
    for user in result["users"]:
        user_dict = user.to_dict()
        users_data.append(UserResponse(**user_dict))
    
    return {
        "code": 200,
        "message": "success",
        "data": {
            "users": users_data,
            "pagination": {
                "page": result["page"],
                "size": result["size"],
                "total": result["total"],
                "total_pages": result["total_pages"]
            }
        }
    }


@users_router.post("/")
@log_api_request("create_user")
async def create_user(
    user_data: UserCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """创建用户"""
    
    # 检查用户名是否已存在
    existing_user = db.query(User).filter(
        User.username == user_data.username,
        User.is_deleted == False
    ).first()
    
    if existing_user:
        raise DataAlreadyExistsError("用户名已存在")
    
    # 检查邮箱是否已存在
    existing_email = db.query(User).filter(
        User.email == user_data.email,
        User.is_deleted == False
    ).first()
    
    if existing_email:
        raise DataAlreadyExistsError("邮箱已存在")
    
    # 创建用户
    user = User(
        username=user_data.username,
        email=user_data.email,
        password=user_data.password,
        full_name=user_data.full_name,
        phone=user_data.phone
    )
    
    db.add(user)
    db.flush()  # 获取用户ID
    
    # 设置角色
    if user_data.role_ids:
        # 简化角色设置，直接使用第一个角色ID对应的角色名称
        # 这里假设role_ids对应角色：1=管理员，2=普通用户
        role_mapping = {1: "admin", 2: "user"}
        role_id = user_data.role_ids[0] if user_data.role_ids else 2
        user.role = role_mapping.get(role_id, "user")
    
    db.commit()
    db.refresh(user)
    
    logger.info(f"创建用户成功: {user.username}")
    
    return {
        "code": 200,
        "message": "用户创建成功",
        "data": UserResponse(**user.to_dict())
    }


@users_router.get("/{user_id}", response_model=UserResponse)
@log_api_request("get_user")
async def get_user(
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取用户详情"""
    # 用户只能查看自己的信息，除非有用户管理权限
    if not current_user.is_superuser and not current_user.has_permission("user_manage"):
        if current_user.id != user_id:
            raise AuthorizationError("只能查看自己的信息")
    
    user = db.query(User).options(joinedload(User.roles)).filter(
        User.id == user_id,
        User.is_deleted == False
    ).first()
    
    if not user:
        raise DataNotFoundError("用户不存在")
    
    return UserResponse(**user.to_dict())


@users_router.put("/{user_id}")
@log_api_request("update_user")
async def update_user(
    user_id: int,
    user_data: UserUpdate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """更新用户"""
    # 用户只能更新自己的信息，除非有用户管理权限
    if not current_user.is_superuser and not current_user.has_permission("user_manage"):
        if current_user.id != user_id:
            raise AuthorizationError("只能更新自己的信息")
        # 非管理员不能修改角色和激活状态
        user_data.role_ids = None
        user_data.is_active = None
    
    user = db.query(User).filter(
        User.id == user_id,
        User.is_deleted == False
    ).first()
    
    if not user:
        raise DataNotFoundError("用户不存在")
    
    # 检查邮箱是否已被其他用户使用
    if user_data.email and user_data.email != user.email:
        existing_email = db.query(User).filter(
            User.email == user_data.email,
            User.id != user_id,
            User.is_deleted == False
        ).first()
        
        if existing_email:
            raise DataAlreadyExistsError("邮箱已被其他用户使用")
    
    # 更新用户信息
    update_data = user_data.dict(exclude_unset=True)
    for field, value in update_data.items():
        if field != "role_ids":
            setattr(user, field, value)
    
    # 更新角色
    if user_data.role_ids is not None:
        # 简化角色设置
        role_mapping = {1: "admin", 2: "user"}
        role_id = user_data.role_ids[0] if user_data.role_ids else 2
        user.role = role_mapping.get(role_id, "user")
    
    db.commit()
    db.refresh(user)
    
    logger.info(f"更新用户成功: {user.username}")
    
    return {
        "code": 200,
        "message": "用户更新成功",
        "data": UserResponse(**user.to_dict())
    }








@users_router.delete("/{user_id}")
@log_api_request("delete_user")
async def delete_user(
    user_id: int,
    current_user: User = Depends(require_admin),
    db: Session = Depends(get_db)
):
    """删除用户"""
    user_service = UserManagementService(db)
    success = user_service.delete_user(user_id=user_id, deleted_by=current_user)
    
    return {"message": "用户删除成功"}




@users_router.post("/{user_id}/reset-password", response_model=PasswordResetResponse)
@log_api_request("reset_user_password")
async def reset_user_password(
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """重置用户密码（仅管理员）"""
    
    # 只有管理员才能重置密码
    if not current_user.is_superuser:
        raise AuthorizationError("只有管理员才能重置用户密码")
    
    user_service = UserManagementService(db)
    new_password = user_service.reset_password(user_id, current_user)
    
    return PasswordResetResponse(
        new_password=new_password,
        message="密码重置成功，请妥善保管新密码"
    )


@users_router.post("/{user_id}/change-password", response_model=PasswordChangeResponse)
@log_api_request("change_user_password")
async def change_user_password(
    user_id: int,
    password_data: PasswordChangeRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """修改用户密码"""
    
    # 用户只能修改自己的密码，除非是管理员
    if not current_user.is_superuser and current_user.id != user_id:
        raise AuthorizationError("只能修改自己的密码")
    
    user_service = UserManagementService(db)
    user_service.change_password(
        user_id=user_id,
        current_password=password_data.current_password,
        new_password=password_data.new_password,
        changed_by=current_user
    )
    
    return PasswordChangeResponse(message="密码修改成功")